package com.zahb.qadx.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.constraintlayout.widget.ConstraintSet;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.githang.statusbar.StatusBarCompat;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseActivity;
import com.zahb.qadx.model.CommonResponse;
import com.zahb.qadx.model.MainFunc2;
import com.zahb.qadx.model.VideoListBean;
import com.zahb.qadx.net.RetrofitService;
import com.zahb.qadx.ui.fragment.MediaPlayerFragment;
import com.zahb.qadx.util.CompatHelper;
import com.zahb.qadx.util.DisplayUtil;
import com.zahb.qadx.util.ImageLoaderKt;
import com.zahb.qadx.util.Tips;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;

public class VideoDetailsActivity extends BaseActivity implements OnRefreshLoadMoreListener,
        OnItemClickListener, MediaPlayerFragment.onFullHalfViewClickListener {

    @BindView(R.id.container_layout)
    ConstraintLayout mContainerLayout;
    @BindView(R.id.media_container)
    FrameLayout mMediaContainer;
    @BindView(R.id.media_bottom_container)
    CoordinatorLayout mMediaBottomContainer;
    @BindView(R.id.tv_title)
    AppCompatTextView mTvTitle;
    @BindView(R.id.tv_profiles)
    AppCompatTextView mTvProfiles;
    @BindView(R.id.tv_remarks)
    AppCompatTextView mTvRemarks;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;

    private BaseQuickAdapter<VideoListBean, BaseViewHolder> mAdapter;

    private ConstraintSet mPortraitConstraintSet;
    private ConstraintSet mLandscapeConstraintSet;

    private View mDecorView;
    private int mDefaultOption;
    private int mNavigationBarColor;

    private MediaPlayerFragment mFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            mTopBarContainer.setVisibility(View.VISIBLE);
            mTopBarDivider.setVisibility(View.VISIBLE);
            mMediaBottomContainer.setVisibility(View.VISIBLE);
            mPortraitConstraintSet.applyTo(mContainerLayout);
            mDecorView.setSystemUiVisibility(mDefaultOption);
            getWindow().setNavigationBarColor(mNavigationBarColor);
            StatusBarCompat.setStatusBarColor(this, Color.WHITE);
        } else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            mTopBarContainer.setVisibility(View.GONE);
            mTopBarDivider.setVisibility(View.GONE);
            mMediaBottomContainer.setVisibility(View.GONE);
            mLandscapeConstraintSet.applyTo(mContainerLayout);
            int option = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            mDecorView.setSystemUiVisibility(option);
            getWindow().setNavigationBarColor(Color.TRANSPARENT);
            StatusBarCompat.setStatusBarColor(this, Color.TRANSPARENT);
        }
    }

    @Override
    public void onBackPressed() {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_video_details;
    }

    @Override
    protected void initViews() {
        mUnbinder = ButterKnife.bind(this);
        VideoListBean bean = (VideoListBean) getIntent().getSerializableExtra("bean");
        if (bean != null) {
            mTvTitle.setText(bean.getName());
            mTvProfiles.setText(CompatHelper.isEmpty(bean.getShortIntroduce()) ? "暂无简介" : bean.getShortIntroduce());
            mTvRemarks.setText(CompatHelper.isEmpty(bean.getRemark()) ? "暂无备注" : bean.getRemark());
            initRecyclerView();
            mRefreshLayout.setEnableLoadMoreWhenContentNotFull(false);
            mRefreshLayout.setOnRefreshLoadMoreListener(this);
            mRefreshLayout.autoRefresh();

            if (CompatHelper.isEmpty(bean.getSourceId())) {
                getVideoId(bean.getId() + "");
            } else {
                replaceMediaFragment(bean.getSourceId());
            }
        }

        initConstraintSets();

        mDecorView = getWindow().getDecorView();
        mDefaultOption = mDecorView.getSystemUiVisibility();
        mNavigationBarColor = getWindow().getNavigationBarColor();
    }

    @Override
    protected int getTitleStringRes() {
        return R.string.video_details;
    }

    @OnClick(R.id.tv_see_more)
    public void onViewClicked() {
        String type = getIntent().getStringExtra("type");
        if (TextUtils.equals(type, TYPE_VIDEO))
            VideoListActivity.actionStartVideo(getContext());
        else if (TextUtils.equals(type, TYPE_AUDIO))
            VideoListActivity.actionStartAudio(getContext());
    }

    private void initRecyclerView() {
        mRecyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));
        final int divider_h = DisplayUtil.dip2px2(5.5f);
        final int divider_v = DisplayUtil.dip2px(16.5f);
        RecyclerView.ItemDecoration decoration = new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                if (parent.getAdapter() == null) return;
                outRect.set(0, 0, 0, 0);
                if (parent.getChildAdapterPosition(view) % 2 == 0) {// 左边
                    outRect.right = divider_h;
                } else if (parent.getChildAdapterPosition(view) % 2 == 1) {// 右边
                    outRect.left = divider_h;
                }
                if (parent.getChildAdapterPosition(view) >= 2) {
                    outRect.top = divider_v;
                }
            }
        };
        mRecyclerView.addItemDecoration(decoration);
        mAdapter = new BaseQuickAdapter<VideoListBean, BaseViewHolder>(R.layout.item_grid_videos) {
            @Override
            protected void convert(@NotNull BaseViewHolder baseViewHolder, VideoListBean bean) {
                ImageLoaderKt.loadImageSameCorners(baseViewHolder.getView(R.id.iv_icon),
                        CompatHelper.isEmpty(bean.getCovenImage()) ? "20200914/1600056121587689.jpg" : bean.getCovenImage(), 5f);
                baseViewHolder.setText(R.id.tv_title, bean.getName())
                        .setText(R.id.tv_sub_title, CompatHelper.isEmpty(bean.getShortIntroduce())
                                ? "该视频暂无简介" : bean.getShortIntroduce());
            }
        };
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(this);
    }

    private void initConstraintSets() {
        mPortraitConstraintSet = new ConstraintSet();
        mPortraitConstraintSet.clone(mContainerLayout);

        mLandscapeConstraintSet = new ConstraintSet();
        mLandscapeConstraintSet.clone(mContainerLayout);

        mLandscapeConstraintSet.clear(R.id.media_container);
        mLandscapeConstraintSet.connect(R.id.media_container, ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START);
        mLandscapeConstraintSet.connect(R.id.media_container, ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END);
        mLandscapeConstraintSet.connect(R.id.media_container, ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP);
        mLandscapeConstraintSet.connect(R.id.media_container, ConstraintSet.BOTTOM, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM);
    }

    private void refreshVideoData(RefreshLayout refreshLayout) {
        Observable<CommonResponse<ArrayList<VideoListBean>>> observable;
        String type = getIntent().getStringExtra("type");
        if (TextUtils.equals(type, TYPE_VIDEO))
            observable = RetrofitService.getNetService().getGreatVideos();
        else if (TextUtils.equals(type, TYPE_AUDIO))
            observable = RetrofitService.getNetService().getGreatAudios();
        else
            return;
        addDisposable(observable.observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    refreshLayout.finishRefresh();
                    if (response.getStatusCode() == 200) {
                        mAdapter.setList(response.getData());
                    } else {
                        showBindToast(response.getErrorInfo());
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    refreshLayout.finishRefresh();
                    Tips.RequestError(getActivity());
                }));
    }

    private void getVideoId(String materialId) {
        addDisposable(RetrofitService.getNetService().postMaterialInfo(materialId)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.getStatusCode() == 200) {
                        replaceMediaFragment(response.getData().getSourceId());
                    } else {
                        showBindToast(response.getErrorInfo());
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    Tips.RequestError(getActivity());
                }));
    }

    private void replaceMediaFragment(String sourceId) {
        String type = getIntent().getStringExtra("type");
        boolean isAudio = false;
        if (TextUtils.equals(type, TYPE_AUDIO))
            isAudio = true;
        if (mFragment == null) {
            mFragment = MediaPlayerFragment.newInstance(sourceId, isAudio);
            mFragment.setOnFullHalfViewClickListener(VideoDetailsActivity.this);
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.media_container, mFragment)
                    .commitAllowingStateLoss();
        } else {
            mFragment.changeMedia(sourceId, isAudio);
        }
    }

    public static final String TYPE_VIDEO = "video";
    public static final String TYPE_AUDIO = "audio";

    public static void actionStart(Context context, VideoListBean bean, String type) {
        Intent intent = new Intent(context, VideoDetailsActivity.class);
        intent.putExtra("bean", bean);
        intent.putExtra("type", type);
        context.startActivity(intent);
    }

    public static void actionStart(Context context, MainFunc2 mainFunc2, String type) {
        VideoListBean bean = new VideoListBean();
        bean.setCovenImage(mainFunc2.getIcon());
        bean.setName(mainFunc2.getTitle());
        bean.setId(mainFunc2.getSourceId());
        actionStart(context, bean, type);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        refreshLayout.finishLoadMore(1000);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        refreshVideoData(refreshLayout);
    }

    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        VideoListBean bean = mAdapter.getItem(position);
        mTvTitle.setText(bean.getName());
        mTvProfiles.setText(CompatHelper.isEmpty(bean.getShortIntroduce()) ? "暂无简介" : bean.getShortIntroduce());
        mTvRemarks.setText(CompatHelper.isEmpty(bean.getRemark()) ? "暂无备注" : bean.getRemark());
        if (CompatHelper.isEmpty(bean.getSourceId())) {
            getVideoId(bean.getId() + "");
        } else {
            replaceMediaFragment(bean.getSourceId());
        }
    }

    @Override
    public void onRequestFull(ImageView view) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }

    @Override
    public void onRequestHalf(ImageView view) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }
}
